<template>
  <div class="answer-list">
    <!-- 回答列表头部 -->
    <div class="answer-list-header">
      <h3 class="answer-count">{{ total }} A response</h3>
      <div class="sort-options">
        <div class="el-radio-group">
          <label
            class="el-radio-button"
            :class="{ 'is-active': currentSort === 'latest' }"
          >
            <input
              class="el-radio-button__original-radio"
              type="radio"
              name="answer-sort"
              value="latest"
              v-model="currentSort"
              @change="handleSortChange($event.target.value)"
            />
            <span class="el-radio-button__inner">latest</span>
          </label>
          <label
            class="el-radio-button"
            :class="{ 'is-active': currentSort === 'hot' }"
          >
            <input
              class="el-radio-button__original-radio"
              type="radio"
              name="answer-sort"
              value="hot"
              v-model="currentSort"
              @change="handleSortChange($event.target.value)"
            />
            <span class="el-radio-button__inner">Hottest</span>
          </label>
          <label
            class="el-radio-button"
            :class="{ 'is-active': currentSort === 'best' }"
          >
            <input
              class="el-radio-button__original-radio"
              type="radio"
              name="answer-sort"
              value="best"
              v-model="currentSort"
              @change="handleSortChange($event.target.value)"
            />
            <span class="el-radio-button__inner">Best</span>
          </label>
        </div>
      </div>
    </div>

    <!-- 回答列表 -->
    <div class="answer-items" v-loading="loading">
      <AnswerCard
        v-for="answer in answers"
        :key="answer.id"
        :answer="answer"
        :question-author-id="questionAuthorId"
        @like="handleAnswerLike"
        @dislike="handleAnswerDislike"
        @delete="handleAnswerDelete"
        @edit="handleAnswerEdit"
        @set-best="handleSetBestAnswer"
        @comment="handleAnswerComment"
      />

      <!-- 空状态 -->
      <div v-if="!loading && answers.length === 0" class="empty-state">
        <el-empty description="haven't answered yet">
          <el-button type="primary" @click="$emit('write-answer')">
            Write the first answer
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import AnswerCard from "./AnswerCard.vue";
import {
  deleteAnswer,
  getAnswerList,
  setBestAnswer,
  toggleDislikeAnswer,
  toggleLikeAnswer,
} from "@/api/answer";

// Props
const props = defineProps({
  questionId: {
    type: String,
    required: true,
  },
  questionAuthorId: {
    type: String,
    default: "",
  },
  refreshTrigger: {
    type: Number,
    default: 0,
  },
});

// Emits
const emit = defineEmits(["write-answer", "answer-deleted", "answer-updated"]);

// 响应式数据
const loading = ref(false);
const answers = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const currentSort = ref("latest");

// 监听刷新触发器
watch(
  () => props.refreshTrigger,
  () => {
    if (props.refreshTrigger > 0) {
      loadAnswers();
    }
  }
);

// 监听问题ID变化
watch(
  () => props.questionId,
  () => {
    if (props.questionId) {
      currentPage.value = 1;
      loadAnswers();
    }
  }
);

// 生命周期
onMounted(() => {
  if (props.questionId) {
    loadAnswers();
  }
});

// 加载回答列表
const loadAnswers = async () => {
  if (!props.questionId) return;

  try {
    loading.value = true;
    const response = await getAnswerList({
      questionId: props.questionId,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      sortType: currentSort.value,
    });

    if (response.code === 200) {
      answers.value = response.data.data || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || "加载回答列表失败");
    }
  } catch (error) {
    console.error("加载回答列表失败:", error);
    ElMessage.error("加载回答列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理排序变化
const handleSortChange = (sortType) => {
  currentSort.value = sortType;
  currentPage.value = 1;
  loadAnswers();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadAnswers();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadAnswers();
};

// 处理回答点赞
const handleAnswerLike = async (answerId, isLiked) => {
  try {
    const response = await toggleLikeAnswer(answerId);
    if (response.code === 200) {
      const answer = answers.value.find((a) => a.id === answerId);
      if (answer) {
        const wasDisliked = answer.isDisliked;

        // 更新点赞状态
        answer.isLiked = !isLiked;
        answer.likeCount += answer.isLiked ? 1 : -1;

        // 如果之前是踩状态，自动取消踩（后端已处理，前端同步状态）
        if (answer.isLiked && wasDisliked) {
          answer.isDisliked = false;
          answer.dislikeCount = Math.max(0, answer.dislikeCount - 1);
        }
      }
      ElMessage.success(answer.isLiked ? "点赞成功" : "已取消点赞");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理回答踩
const handleAnswerDislike = async (answerId, isDisliked) => {
  try {
    const response = await toggleDislikeAnswer(answerId);
    if (response.code === 200) {
      const answer = answers.value.find((a) => a.id === answerId);
      if (answer) {
        const wasLiked = answer.isLiked;

        // 更新踩状态
        answer.isDisliked = !isDisliked;
        answer.dislikeCount += answer.isDisliked ? 1 : -1;

        // 如果之前是赞状态，自动取消赞（后端已处理，前端同步状态）
        if (answer.isDisliked && wasLiked) {
          answer.isLiked = false;
          answer.likeCount = Math.max(0, answer.likeCount - 1);
        }
      }
      ElMessage.success(answer.isDisliked ? "已踩" : "已取消踩");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("踩操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理删除回答
const handleAnswerDelete = async (answerId) => {
  try {
    const response = await deleteAnswer(answerId);
    if (response.code === 200) {
      ElMessage.success("删除成功");
      emit("answer-deleted");
      // 重新加载当前页，如果当前页没有数据了，回到上一页
      if (answers.value.length === 1 && currentPage.value > 1) {
        currentPage.value -= 1;
      }
      loadAnswers();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    console.error("删除回答失败:", error);
    ElMessage.error("删除失败");
  }
};

// 处理编辑回答
const handleAnswerEdit = (answerId) => {
  // TODO: 实现编辑功能
  ElMessage.info("编辑功能开发中");
};

// 处理设置最佳答案
const handleSetBestAnswer = async (answerId) => {
  try {
    const response = await setBestAnswer(answerId);
    if (response.code === 200) {
      ElMessage.success("设置最佳答案成功");
      emit("answer-updated");
      loadAnswers();
    } else {
      ElMessage.error(response.message || "设置失败");
    }
  } catch (error) {
    console.error("设置最佳答案失败:", error);
    ElMessage.error("设置失败");
  }
};

// 处理回答评论
const handleAnswerComment = (answerId) => {
  // 评论功能已在 AnswerCard 组件中实现
  console.log("切换评论显示状态:", answerId);
};

// 暴露方法给父组件
defineExpose({
  loadAnswers,
  refresh: loadAnswers,
});
</script>

<style lang="scss" scoped>
.answer-list {
  margin-top: 24px;
}

.answer-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.answer-count {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #1a1a1a;
}

.sort-options {
  .el-radio-group {
    :deep(.el-radio-button__inner) {
      border-color: #e1e1e1;
      color: #666;

      &:hover {
        color: #b92b27;
      }
    }

    :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
      background-color: #b92b27;
      border-color: #b92b27;
      color: white;
    }
  }
}

.answer-items {
  min-height: 200px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}
</style>
